import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, App} from 'ionic-angular';
import {FormComponentService} from "../../admin/form-component/form-component.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {AppConfig} from "../../../app/appConfig";
import {HttpClient} from "@angular/common/http";
import {AppUrl, STORAGE_KEY, TIME_OUT} from "../../../app/app.general";
import {CommonService} from "../../../app/common.service";
import {ACLService} from "../../../app/acl/acl.service";
import {Login} from "../../pages";

/**
 * Generated class for the ResetPassowrdPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-reset-passowrd',
  templateUrl: 'reset-passowrd.html',
})
export class ResetPassowrdPage {
  account =
    [
      {
        key: 'passwordNew',
        type: 'ion-input',
        label: '新密码',
        inputType: 'password'
      },
      {
        key: 'passwordNewConfirm',
        type: 'ion-input',
        label: '确认新密码',
        inputType: 'password'
      }
    ];

  accountForm: FormGroup;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formService: FormComponentService, private fb: FormBuilder, private appConfig: AppConfig, private http: HttpClient, private commonService: CommonService, private acl: ACLService, private app: App) {
    this.accountForm = this.fb.group({
      passwordNew: ['', [Validators.required, Validators.maxLength(20), Validators.minLength(6)]],
      passwordNewConfirm: ['', [Validators.required, Validators.maxLength(20), Validators.minLength(6)]],
    });
    this.formService.group = this.accountForm;
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ResetPassowrdPage');
  }

  output(res: any) {
    this.appConfig.presentLoading('正在修改...');
    if (res.passwordNew === res.passwordNewConfirm) {
      this.http.post(AppUrl.user.resetPassword, res).timeout(TIME_OUT).subscribe(res => {
        let temp: any = res;
        if (temp.code === 200) {
          this.appConfig.presentToast(temp.msg);
          this.acl.clearAll();
          localStorage.setItem(STORAGE_KEY.token, '');

          this.app.getRootNav().setRoot(Login, {}, {animate: true, direction: 'enter'}).then(() => {
          });
        }
        else {
          this.appConfig.presentToast(temp.msg);
        }
        this.appConfig.loader.dismiss();
      }, reject => {
        this.commonService.httpError(reject);
        this.appConfig.loader.dismiss();
      });
    }
    else {
      this.appConfig.presentToast("两次密码输入不一致,请检查");
      this.appConfig.loader.dismiss();
    }
  }

}
